import { assign, setup } from 'xstate';
import type { TodoItem } from './todosMachine';

export const todoMachine = setup({
  types: {
    context: {} as {
      initialTitle: string;
      title: string;
    },
    events: {} as
      | {
        type: 'edit';
      }
      | {
        type: 'blur';
      }
      | {
        type: 'cancel';
      }
      | {
        type: 'change';
        value: string;
      },
    input: {} as {
      todo: TodoItem;
    }
  },
  actions: {
    onCommit: () => { },
    focusInput: () => { }
  }
}).createMachine({
  id: 'todo',
  initial: 'reading',
  context: ({ input }) => ({
    initialTitle: input.todo.title,
    title: input.todo.title
  }),
  states: {
    reading: {
      on: {
        edit: 'editing'
      }
    },
    editing: {
      entry: [
        assign({
          initialTitle: ({ context }) => context.title
        }),
        'focusInput'
      ],
      on: {
        blur: {
          target: 'reading',
          actions: 'onCommit'
        },
        cancel: {
          target: 'reading',
          actions: assign({
            title: ({ context }) => context.initialTitle
          })
        },
        change: {
          actions: assign({
            title: ({ event }) => event.value
          })
        }
      }
    }
  }
});
